import React, { Component } from 'react';
import {
	StyleSheet, View, Image, ScrollView, Text, TouchableOpacity, DeviceEventEmitter
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { ApproveButtonNew } from './_component/approveButtonNew';
import { ApproveRefuseModal } from './modals/refuse';
import { ProductSection } from './_component/ProductSection';
import { OrderBaseSection } from './_component/OrderBaseSection';
import { StateSectionNew } from './_component/StateSectionNew';
import { ViewList } from './_component/ViewList';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import navigationSeevice from '../../../../components/navigation/navigationSeevice';
import OrderApproveService from '../_common/service';
import { CREDIT_TYPES } from '../../../../config/definition';
import { CURRENCY } from '../../../../utils/helper';
import MethodUtil from '../../../../utils/MethodUtil';
import ToastUtil from '../../../../utils/toast';
import { BockCpt } from './_component/BockCpt';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http'
import Dictionary from '../../../../utils/dictionary';

const scale = GLOBAL.SCALE;


export class OrderApprovePage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			header: null
		}
	};

	requesting;
	constructor(props) {
		super(props);
		this.orderId = props.navigation.state.params.paramsData.orderId;
		this.businessKey = props.navigation.state.params.paramsData.businessKey;
		this.taskId = props.navigation.state.params.paramsData.taskId;
		this.formKey = props.navigation.state.params.paramsData.formKey;
		this.auditResultName = props.navigation.state.params.paramsData.auditResultName;
		this.approveType = props.navigation.state.params.paramsData.approveType || 'O';
		this.taskType = props.navigation.state.params.paramsData.taskType || 'ApprovalDefaultPage';
		this.choice = props.navigation.state.params.choice || {};
		this.state = {
			data: {},
			loaded: false,
			profitList: [],
			refuseModalVisible: false,
			deliveryPlan: {
			},
			trustData: {},
			companyInfo: {},
			buyCostInfo: null,
			inPayTypeData: [],
			QHPayTypeData: []
		}
		DeviceEventEmitter.addListener('showCostDetails', async () => {
			if (this.ScrollView) {
				await this.ScrollView.scrollToEnd()
				this.ChangeVisible(true)
			}
		})
	}

	componentWillMount() {
		this._getDetailData(this.orderId);//详情数据
		this._getProfitData(this.orderId);//盈利数据
		this._getDeliveryPlan(this.orderId);//费用成本预估及交货计划
		this._getPayInit()
	}

	//获取盈利数据
	async _getProfitData(orderId) {
		let responseData = await OrderApproveService.getProfitData({ orderId });
		if (responseData) {
			this.setState({
				profitList: responseData
			})
		}
	}

	//初始化详情数据
	async _getDetailData(orderId) {
		this.setState({
			loaded: true
		});
		let response = {
			orderId: orderId,
			taskId: this.taskId
		}
		let responseData = await HTTP.GET(API_GENERATE(API.ORDER_APPROVAL_DERAIL), response);
		let buyCostInfo = await HTTP.POST(API_GENERATE(API.BUY_COST_INFO + `/${orderId}`));

		// let responseData = await OrderApproveService.getApproveDetail({ approveType: this.approveType }, {
		// 	orderId,
		// 	queryType: 'ORDER_ALL_INFO',
		// 	taskId: this.taskId
		// });
		this.setState({
			loaded: false
		});
		if (responseData) {
			this.setState({
				data: responseData,
				buyCostInfo
			}, () => {
				this._getTrustList()
			})
		}
	}

	async _getDeliveryPlan(orderId) {
		let deliveryPlan = await HTTP.GET(API_GENERATE(API.DELIVERY_PLAN) + `?orderId=${orderId}`);
		this.setState({
			deliveryPlan
		});
	}

	async _getTrustList() {
		let { companyId, orderType, corpId, bizMode, oppoOrderInfo } = this.state.data
		let orderTypeBiz, companyIdBiz
		if (bizMode === 1) {
			orderTypeBiz = 'P'
			if (orderType == 'P') {
				companyIdBiz = companyId
			}
			else {
				companyIdBiz = oppoOrderInfo.companyId
			}
		}
		else {
			orderTypeBiz = orderType
			companyIdBiz = companyId
		}
		let trustSend = {
			companyId: companyIdBiz,
			corpType: orderTypeBiz == 'P' ? '1' : '2',
			orderType: orderTypeBiz
		}
		let companySend = {
			companyId: companyIdBiz,
			corpId: corpId,
			orderType: orderTypeBiz
		}
		let trustData = await HTTP.POST(API_GENERATE(API.ORDER_TRUST_LIST), trustSend);
		let companyInfo = await HTTP.GET(API_GENERATE(API.COMPANY_ORDER_INFO), companySend);
		this.setState({
			trustData,
			companyInfo
		})
	}


	approveAgree() {
		this.isAgreed = '1';
		this.remark = "";
		this.setState({
			refuseModalVisible: true
		})
	}

	approveRefuse() {
		this.isAgreed = '0';
		this.remark = "";
		this.setState({
			refuseModalVisible: true
		})
	}

	async _fetchApproval() {
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;

		const responseData = await OrderApproveService.goApprove({ approveType: this.approveType }, {
			businessKey: this.businessKey,
			taskId: this.taskId,
			formKey: this.formKey,
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
			corpId: this.choice.corpId,
		});
		this.setState({ loaded: false });
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => { this._goBack(); })
		} else {
			this.requesting = false;
		}
	}

	// 返回上一个页面
	_goBack = () => {
		setTimeout(() => {
			this.requesting = false;
		}, 1000)
		this.props.navigation.navigate('ApproveListPageNew', { choice: this.choice });
	}
	// 支付 
	async _getPayInit() {
		//付款类型
		let inPayTypeData = await Dictionary.get('EC_PAY_TYPE'); // 付款类型
		let QHPayTypeData = await Dictionary.get('EC_QH_PAY_TYPE');// 泉化-付款类型
		this.setState({
			inPayTypeData,
			QHPayTypeData
		})
	}
	//支付信息
	_viewPay = () => {
		let { deliveryPlan, data, inPayTypeData, QHPayTypeData } = this.state;
		return (
			<ViewList deliveryPlan={deliveryPlan} data={data} type={'pay'} inPayTypeData={inPayTypeData} QHPayTypeData={QHPayTypeData} />
		)
	}
	//运输信息
	_viewCar = () => {
		let { deliveryPlan, data } = this.state;
		return (
			<ViewList deliveryPlan={deliveryPlan} data={data} type={'car'} />
		)
	}
	//交货计划
	_viewPlan = () => {
		let { deliveryPlan } = this.state;
		return (
			<ViewList deliveryPlan={deliveryPlan} type={'plan'} />
		)
	}
	//费用成本预估
	_viewEstimate = () => {
		let { deliveryPlan } = this.state;
		return (
			<ViewList deliveryPlan={deliveryPlan} type={'estimate'} />
		)
	}
	render() {
		let { data, trustData, companyInfo, buyCostInfo, deliveryPlan, inPayTypeData, QHPayTypeData } = this.state;
		let { companyName, orderId, currency,
			processInstanceId, orderItemList, auditRemark, remark,
			bizStaffName, corpName, createTime, bizOrganName, bizMode, isTaskAudit, periodType,
			isAgency, isFuture, longOrderId, isQhXhXsBiz, bizTeamName, organName
		} = data;
		let tCode = 'S';//现货
		if (isAgency == 1) { tCode = 'A' };//代理
		if (bizMode == 1) { tCode = 'C' };//闭口
		if (periodType == 'L') { tCode = 'L' };//长约框架
		if (isFuture == 1) { tCode = 'F' };//远期
		if (longOrderId) { tCode = 'E' };//执行
		if (isQhXhXsBiz === 'Y') { tCode = 'QH' };//泉化销售单
		/*
		 * 背靠背会分别展示采购和销售的基本信息、交货计划
		 * 风控和财务角色都不展示交货计划、关联成交
		 * 风控角色不展示费用预算
		*/
		return (
			<View style={styles.container}>
				<View style={styles.headBox}>
					<View style={styles.topBox}>
						<Common type="headLeft" onPress={() => { navigationSeevice.navigate('ApproveListPageNew', { choice: this.choice || {}, approveType: 'O' }) }} color='#fff' />
						<Text style={styles.topTitle}>成交报告审批</Text>
						<StateSectionNew corpId={this.choice.corpId || null} data={{ orderId, processInstanceId, companyName: companyName ? companyName : this.companyName, auditResultName: this.auditResultName }} approveType={this.approveType} />
					</View>
				</View>
				<ScrollView ref={ref => this.ScrollView = ref}>
					<OrderBaseSection choice={this.choice} propsData={this.props} data={data} taskType={OrderApproveService.TASK_KEY[this.taskType]} trustData={trustData} companyInfo={companyInfo} />
					<View style={{ marginTop: -40 * scale }}>
						{orderItemList && orderItemList.length > 0 ?
							orderItemList.map((item, index) => {
								return (
									<ProductSection orderAllInfo={data} data={item} key={index} currency={currency} corpId={this.choice.corpId || null} createTime={createTime} bizMode={bizMode} propsData={this.props} visible={index === 0 ? true : false} tCode={tCode} />
								)
							}) : null}
					</View>
					{/* {
						inPayTypeData.length > 0 && QHPayTypeData.length > 0 ? */}
					<View>
						<BockCpt data={{
							title: '支付信息',
							visible: true
						}}
							renderView={this._viewPay}
						/>
						<BockCpt data={{
							title: '运输信息',
							visible: true
						}}
							renderView={this._viewCar}
						/>
						<BockCpt data={{
							title: '交货计划',
							visible: false
						}}
							renderView={this._viewPlan}
						/>
						<BockCpt data={{
							title: '费用成本预估(元)',
							visible: false
						}}
							ChangeVisible={(func) => this.ChangeVisible = func}
							renderView={this._viewEstimate}
						/>
					</View>
					{/* : null
					} */}
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>送审备注：</Text>
						<Text style={styles.btmText}>{auditRemark || '-'}</Text>
					</View>
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>合同备注：</Text>
						<Text style={styles.btmText}>{remark || '-'}</Text>
					</View>
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>业务员：</Text>
						<Text style={styles.btmText}>
							{(bizStaffName || bizTeamName || bizOrganName) ? `(${bizStaffName ? bizStaffName + ' | ' : '--'}${bizTeamName ? bizTeamName + ' | ' : '--'}${bizOrganName ? bizOrganName : '--'})` : '--'}
						</Text>
					</View>
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>业务组织：</Text>
						<Text style={styles.btmText}>{corpName || '-'}</Text>
					</View>
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>申请时间：</Text>
						<Text style={styles.btmText}>{createTime || '-'}</Text>
					</View>
					<View style={styles.btmBox}>
						<Text style={styles.btmTitle}>订单部门：</Text>
						<Text style={styles.btmText}>{organName || '-'}</Text>
					</View>
					<View style={{ paddingBottom: 20 }}>
					</View>
				</ScrollView>
				{!isTaskAudit ?
					<View style={{ backgroundColor: '#fff' }}>
						<ApproveButtonNew agreePress={() => { this.approveAgree(); }} refusePress={() => { this.approveRefuse(); }} data={buyCostInfo} />
					</View> : null
				}

				<ApproveRefuseModal
					auditRemark={this.remark}
					visible={this.state.refuseModalVisible}
					titleText={'审批意见'}
					placeholderText={this.isAgreed == '1' ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed == '1' ? '审批同意' : '审批驳回'}
					btnPress={(remark) => {
						this.remark = remark;
						if (!this.remark && OrderApproveService.TASK_KEY[this.taskType] === 'L' && this.isAgreed == '0') {
							this.setState({
								refuseModalVisible: false,
							});
							ToastUtil.showWarning('请输入驳回原因');
							return;
						} else {
							this._fetchApproval();
						}
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
				{
					this.state.loaded ?
						<View style={{ position: 'absolute', height: '100%', width: '100%', top: 0 }}>
							<PageStatusIndex status='loading' />
						</View>
						: null
				}
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#F4F7FE',
	},
	emptyBg: {
		height: 39 * scale,
		backgroundColor: style.color.themeColor,
		marginBottom: 13 * scale,
	},
	borders: {
		borderTopWidth: 12 * scale,
		borderStyle: 'solid',
		borderTopColor: style.color.dullGrey,
	},
	headBox: {
		paddingTop: 40 * scale,
		// height: 160 * scale,
		backgroundColor: style.color.themeColor,
		paddingBottom: 20 * scale,
	},
	topTitle: {
		fontSize: 18 * scale,
		color: '#fff'
	},
	topBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingHorizontal: 18
	},
	bockTitle: {
		fontSize: 12 * scale,
		color: '#000',
		fontWeight: 'bold',
		paddingHorizontal: 12,
		marginBottom: 3
	},
	bockBox: {
		paddingHorizontal: 12,
	},
	bockBefore: {
		paddingHorizontal: 12,
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
	},
	bockText: {
		fontSize: 11 * scale,
		color: '#000',
		lineHeight: 18
	},
	bockCarText: {
		fontSize: 12 * scale,
		color: '#000',
		lineHeight: 18,
	},
	bockCarBox: {
		backgroundColor: '#F4F7FE',
		borderRadius: 6,
		paddingVertical: 9,
		marginTop: 10,
		paddingHorizontal: 12,
	},
	bockAfter: {
		flexDirection: 'row',
		alignItems: 'center',
		flexWrap: 'wrap',
		borderRadius: 2,
		borderColor: '#E02020',
		borderWidth: 1,
		marginTop: 20,
		marginHorizontal: 6,
		paddingHorizontal: 5,
		paddingVertical: 10,
	},
	bockAfterTitle: {
		fontSize: 12 * scale,
		color: '#E02020',
		backgroundColor: '#fff',
		position: 'absolute',
		paddingHorizontal: 5,
		left: 10,
		top: -8
	},
	bockRow: {
		flexDirection: 'row',
		alignItems: 'center',
		marginTop: 5
	},
	bockRowTitle: {
		fontSize: 12,
		color: '#a5a6a7',
		width: 100,
		marginRight: 10,
		textAlign: 'right'
	},
	bockRowText: {
		fontSize: 12,
		color: '#000',
	},
	btmBox: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingHorizontal: 13,
		marginTop: 10
	},

	btmTitle: {
		fontSize: 12 * scale,
		color: '#080808',
		width: 62 * scale,
		marginRight: 10,
		textAlign: 'right'
	},
	btmText: {
		fontSize: 12,
		color: '#080808',
		width: '80%'
	},
	modeType: {
		width: 20,
		borderRadius: 2,
		paddingHorizontal: 4,
		paddingVertical: 2,
		marginRight: 10,
		backgroundColor: '#F7B500'
	},
	modeTypeSale: {
		width: 20,
		borderRadius: 2,
		paddingHorizontal: 4,
		paddingVertical: 2,
		marginRight: 10,
		backgroundColor: '#3E7406'
	},
	modeTypeText: {
		fontSize: 11,
		color: '#FFFFFF'
	},
	flexRow: {
		flexDirection: 'row',
		marginLeft: 14,
		alignItems: 'flex-start'
	}
})